package com.hanko.web;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @desc: SpringBoot+RestClient(RestHighLevelClient) 适用于高级搜索
 * @author: luodengxiong
 * @date: 2020-12-22 9:17:17
 **/
@Api(tags = "RestHighLevelClient 操作方式")
@RestController
@RequestMapping("/RestHighLevelClient")
public class RestHighLevelClientController {

    @Qualifier("elasticsearchClient")
    @Autowired
    RestHighLevelClient restHighLevelClient;

    @ApiOperation(value = "普通搜索")
    @GetMapping("search")
    public String search() throws IOException {
        SearchRequest searchRequest = new SearchRequest("high-index01");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        searchRequest.source(searchSourceBuilder);

        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        StringBuilder sv = new StringBuilder();
        searchResponse.getHits().forEach(res -> {
            sv.append(res.toString());
        });
        return sv.toString();
    }

}
